package cn.loveq.android.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.http.AndroidHttpClient;
import android.os.Environment;
import android.util.Log;

public class Downloader {
	public final static String SDCARD_PATH = Environment.getExternalStorageDirectory().getPath();// sdk位置
	public final static String IMAGES_FILE_NAME = "loveq";// 保存图片的文件夹名
	private final static String LOG_TAG = "downloader";

	public static void downloadBitmap(String url, String phrase) {
		final int IO_BUFFER_SIZE = 4 * 1024;

		// AndroidHttpClient is not allowed to be used from the main thread
		final HttpClient client = new DefaultHttpClient();
		final HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					// return BitmapFactory.decodeStream(inputStream);
					// Bug on slow connections, fixed in future release.
					// Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));

					Log.i("test", "下载图标");
					putImageToFileCache(url, phrase, inputStream);// 把图片保存到本地
				} catch (Exception e) {
					System.gc();

				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
		} catch (IllegalStateException e) {
			getRequest.abort();
			Log.w(LOG_TAG, "Incorrect URL: " + url);
		} catch (Exception e) {
			getRequest.abort();
			Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
		} finally {
			if ((client instanceof AndroidHttpClient)) {
				((AndroidHttpClient) client).close();
			}
		}
	}

	public static String md5(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			String result = byte2hex(md.digest(str.getBytes("utf-8")));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 二行制转字符串
	 */
	private static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}

		return hs.toString().toUpperCase();
	}

	static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break; // we reached EOF
					} else {
						bytesSkipped = 1; // we read one byte
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

	public static void putImageToFileCache(String url, String phares, InputStream input) {

		OutputStream os = null;
		String fileName = phares;
		Log.i("test", fileName);
		BufferedOutputStream bos = null;
		try {

			os = getOutputStream(fileName);
			bos = new BufferedOutputStream(os);
			byte[] buffer = new byte[1024];
			int length;
			while ((length = input.read(buffer)) != -1) {
				bos.write(buffer, 0, length);
			}

			// return ApplicationInfo.context.getFilesDir().getAbsolutePath() + "/" + fileName;

		} catch (Exception e) {

			e.printStackTrace();

		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}

		}

	}

	public static OutputStream getOutputStream(String fileName) {

		try {
			OutputStream outputStream = null;
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 内存卡存在
				File dir = new File(SDCARD_PATH + "/" + IMAGES_FILE_NAME);
				if (!dir.exists()) {
					dir.mkdirs();
				}

				File file = new File(SDCARD_PATH + "/" + IMAGES_FILE_NAME + "/" + fileName);
				// file.createNewFile();
				outputStream = new FileOutputStream(file);

			}
			return outputStream;
		} catch (Exception e) {

			e.printStackTrace();
		}

		return null;
	}

}
